import {eventBus} from '../utils/event';
import { SmileOutlined, UserOutlined, LoginOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { useNavigate, } from 'react-router-dom';
import { Dropdown, Space, Modal, Button, Form, Input, message } from 'antd';
import { userCheckPasswordApi, userChangePasswordApi } from '../apis/user'
import { Avatar } from 'antd';
import React from 'react'
export default function () {
  //强制更新
  const[,setCount]=React.useState(0)
  //接收头像更新时间
  React.useEffect(() => {
    eventBus.addListener('updateProfile', function () {
      setCount(c=>c+1)
    })
  },[])
  const navigate = useNavigate()
  const onFinish = (values: any) => {
    userChangePasswordApi({ username: username, password: values.password }).then(
      res => {
        message.success('修改成功')
        setIsModalOpen(false)
        localStorage.clear()
        setTimeout(() => {
          navigate('/')
        }, 1500)
      }
    )
  };
  const logOut = () => {
    message.success('退出成功')
    localStorage.clear()
    navigate('/')
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [resOld, setResOld] = React.useState(false)
  const showModal = () => {
    setIsModalOpen(true);
  };
  const { username, avatar } = JSON.parse(localStorage.userInfo);
  //图片基础链接
  const baseImgUrl = 'http://xawn.f3322.net:8002/distremote/static/avatar/'
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
          个人中心
        </a>
      ),
      icon: <UserOutlined />
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" onClick={showModal}>
          修改密码
        </a>
      ),
      icon: <SmileOutlined />,

    },
    {
      key: '3',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          系统定制
        </a>
      ),
      icon: <SettingOutlined />

    },
    {
      key: '4',
      label: (
        <a onClick={logOut}>
          退出登录
        </a>
      ),
      icon: <LoginOutlined />
    },
  ];
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //验证旧密码
  const validatePass = (rule: any, value: any, callback: any) => {
    userCheckPasswordApi({ username: username, password: value })
      .then(res => {
        if (!res) {
          callback(new Error('旧密码不正确！'))
        } else {
          callback()
        }
      })
  }
  return (
    <>
      <Dropdown menu={{ items }}>
        {/* 头像 */}
        <a onClick={(e) => e.preventDefault()} className='avatar'>
          <Space>
            <Avatar size={40} src={baseImgUrl + avatar} />
            <div>{username}</div>
            {/* <DownOutlined /> */}
          </Space>
        </a>
      </Dropdown>
      <Modal title="修改密码" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
        footer={null}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          validateTrigger={['onBlur']}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入旧密码' },
            { required: true, validator: validatePass },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[{ required: true, message: '请输入新密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="conFirmPassword"
            rules={[{ required: true, message: '请输入确认密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('新旧密码不一样'));
              },
            }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>

    </>
  )
}


